//
//  BDUserModel.m
//  BadBoy
//
//  Created by 余勇 on 2017/3/8.
//  Copyright © 2017年 niusaibing. All rights reserved.
//

#import "BDUserModel.h"
#import "BDFMDBTool.h"
#import "BDMD5.h"
//#import "BDChatGroupModel.h"
#import <JMessage/JMessage.h>

#define CurrentUserPath     [CachePaths stringByAppendingPathComponent:@"currentUser.data"]
#define TouristsUserPath     [CachePaths stringByAppendingPathComponent:@"touristsUser.data"]

@interface BDUserModel ()

//- (RACCommand *)_getFriendList;
//- (RACCommand *)_getGroupList;
- (RACCommand *)_loginIM;

@end

@implementation BDUserModel

MJCodingImplementation

- (NSString *)cover{
    if (_cover ==nil) {
        return @"";
    }
    return _cover;
}

//+ (BDUserModel *)creatWithFriendInfo:(BDFridentInfo *)friendInfo{
//    BDUserModel *user = [[BDUserModel alloc] init];
//    user.user_id = friendInfo.user_id.integerValue;
//    user.nickname = friendInfo.nickname;
//    user.email = friendInfo.email;
//    user.cover = friendInfo.cover;
//    user.status = friendInfo.status.integerValue;
//    user.is_auth = friendInfo.is_auth.boolValue;
//    user.birthday = friendInfo.birthday;
//    user.true_name = friendInfo.true_name;
//    user.sex = friendInfo.sex.integerValue;
//    user.address_id = friendInfo.address_id.integerValue;
//    user.mobile = friendInfo.mobile;
//    user.vip_level = friendInfo.vip_level.integerValue;
//    return user;
//}

+ (BDUserModel *)getTouristsUser{
    return [NSKeyedUnarchiver unarchiveObjectWithFile:TouristsUserPath];
}

- (void)saveTouristsUser{
    [NSKeyedArchiver archiveRootObject:self toFile:TouristsUserPath];
}

+ (BDUserModel *)getCurrentUser{
    return [NSKeyedUnarchiver unarchiveObjectWithFile:CurrentUserPath];
}
+ (NSString *)getHeaderValidation{
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"loginToken"];
    if (![token isNotEmpty]) {
        return nil;
    }
    return [NSString stringWithFormat:@"Bearer %@", token];
}
- (BOOL)saveCurrentUser{
    if ([self.access_token isNotEmpty]) {
        [[NSUserDefaults standardUserDefaults] setObject:self.access_token forKey:@"loginToken"];
    }
    return [NSKeyedArchiver archiveRootObject:self toFile:CurrentUserPath];
}

+ (void)getUserIfOverdueAfterBlock:(void(^)())afterBlock{
    BDUserModel *user = [self getCurrentUser];
    if (user.is_guest == YES || user == nil) {
        [MBManager showLoadingAlert:ASLocalizedString(@"正在加载")clickHidden:NO clickBlock:nil];
        NSString *url = [NSString stringWithFormat:@"%@guest", KBDBaseURL];
        NSDictionary *para = @{@"guest_id":[[[UIDevice currentDevice] identifierForVendor] UUIDString]};
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:nil automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            [MBManager hideAlert];
            BDUserModel *newUser = [BDUserModel mj_objectWithKeyValues:x];
            newUser.unique_id = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
            [newUser saveCurrentUser];
            [newUser saveTouristsUser];
            if (afterBlock) {
                afterBlock();
            }
        }];
    }else{
        if (afterBlock) {
            afterBlock();
        }
    }
}

+ (void)loginUserWithAccount:(NSString *)account code:(NSString *)code loginType:(BDLoginType)loginType completionHandler:(BDBlockHandler)completionHandler{
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    NSMutableDictionary *para = @{@"id":account,
                           @"key":code,
                           @"grant_type":@"password",
                           @"unique_id":idfv}.mutableCopy;
    if (loginType == BDLoginTypeThirdPart) {
        [para setObject:@"third_party" forKey:@"auth_type"];
        [para setObject:@"weixin" forKey:@"third_party"];
    }else if (loginType == BDLoginTypeVerificationCode){
        [para setObject:@"sms" forKey:@"auth_type"];
    }else{
        [para setObject:@"password" forKey:@"auth_type"];
    }
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"firstInstall"] == nil) {
        [para setObject:@"1" forKey:@"install"];
    }
    
    NSString *url = [NSString stringWithFormat:@"%@login",KBDBaseURL];
    RACCommand *command = [BDNetworkingServer yy_POST:url parameters:para validation:nil automaticProcessingError:NO];
    RACSignal *signal = [command execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        BDUserModel *user = [BDUserModel mj_objectWithKeyValues:x];
        if (![user.nickname isNotEmpty]) {
            NSError *newError = [NSError errorWithDomain:NSCocoaErrorDomain code:BDLoginErrorNotCompletionInfo userInfo:nil];
            if (completionHandler) {
                completionHandler(x, newError);
            }
        }else{
            [user saveCurrentUser];
            RACSignal *loginImSignal = [[user _loginIM] execute:nil];
            [loginImSignal subscribeCompleted:^{
//                RACSignal *getFriednSignal = [[user _getFriendList] execute:nil];
//                RACSignal *getGroupGignal = [[user _getGroupList] execute:nil];
                //
//                [[RACSignal merge:@[getFriednSignal, getGroupGignal]] subscribeCompleted:^{
//                    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"firstInstall"];
//                    if (completionHandler) {
//                        completionHandler(x, nil);
//                    }
//                }];
//                [getGroupGignal subscribeError:^(NSError * _Nullable error) {
//                    [self loginOut];
//                    if (completionHandler) {
//                        completionHandler(nil, error);
//                    }
//                }];
//                [getFriednSignal subscribeError:^(NSError * _Nullable error) {
//                    [self loginOut];
//                    if (completionHandler) {
//                        completionHandler(nil, error);
//                    }
//                }];
                [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"firstInstall"];
                if (completionHandler) {
                    completionHandler(x, nil);
                }
            }];
            [loginImSignal subscribeError:^(NSError * _Nullable error) {
                BDUserModel *tourUser = [BDUserModel getTouristsUser];
                [tourUser saveCurrentUser];
                if (completionHandler) {
                    completionHandler(nil, error);
                }
            }];
        }
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        if (completionHandler) {
            completionHandler(nil, error);
        }
    }];
}

+ (void)registWithPara:(NSMutableDictionary *)para completionHandler:(BDBlockHandler)completionHandler{
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [para setObject:idfv forKey:@"unique_id"];

    NSString *registUrl = [NSString stringWithFormat:@"%@reg", KBDBaseURL];
    RACSignal *registSignal = [[BDNetworkingServer yy_POST:registUrl parameters:para validation:nil automaticProcessingError:YES] execute:nil];
    
    //错误处理
    [registSignal subscribeError:^(NSError * _Nullable error) {
        if (completionHandler) {
            completionHandler(nil, error);
        }
    }];
    
    //正确处理
    [registSignal subscribeNext:^(id  _Nullable x) {
        BDUserModel *user = [BDUserModel mj_objectWithKeyValues:x];
        [user saveCurrentUser];
        RACSignal *loginImSignal = [[user _loginIM] execute:nil];
        [loginImSignal subscribeCompleted:^{
            //                RACSignal *getFriednSignal = [[user _getFriendList] execute:nil];
            //                RACSignal *getGroupGignal = [[user _getGroupList] execute:nil];
            //
            //                [[RACSignal merge:@[getFriednSignal, getGroupGignal]] subscribeCompleted:^{
            //                    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"firstInstall"];
            //                    if (completionHandler) {
            //                        completionHandler(x, nil);
            //                    }
            //                }];
            //                [getGroupGignal subscribeError:^(NSError * _Nullable error) {
            //                    [self loginOut];
            //                    if (completionHandler) {
            //                        completionHandler(nil, error);
            //                    }
            //                }];
            //                [getFriednSignal subscribeError:^(NSError * _Nullable error) {
            //                    [self loginOut];
            //                    if (completionHandler) {
            //                        completionHandler(nil, error);
            //                    }
            //                }];
            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"firstInstall"];
            if (completionHandler) {
                completionHandler(x, nil);
            }
        }];
        [loginImSignal subscribeError:^(NSError * _Nullable error) {
            BDUserModel *tourUser = [BDUserModel getTouristsUser];
            [tourUser saveCurrentUser];
            [MBManager showBriefAlert:ASLocalizedString(@"环信登录失败")clickHidden:NO clickBlock:nil];
        }];
    }];
}

+ (void)completionInfoWithPara:(NSMutableDictionary *)para completionHandler:(BDBlockHandler)completionHandler{
    NSString *url = [NSString stringWithFormat:@"%@user", KBDBaseURL];
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:nil automaticProcessingError:NO] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        BDUserModel *user = [BDUserModel mj_objectWithKeyValues:x];
        [user saveCurrentUser];
        RACSignal *loginImSignal = [[user _loginIM] execute:nil];
        [loginImSignal subscribeCompleted:^{
            //                RACSignal *getFriednSignal = [[user _getFriendList] execute:nil];
            //                RACSignal *getGroupGignal = [[user _getGroupList] execute:nil];
            //
            //                [[RACSignal merge:@[getFriednSignal, getGroupGignal]] subscribeCompleted:^{
            //                    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"firstInstall"];
            //                    if (completionHandler) {
            //                        completionHandler(x, nil);
            //                    }
            //                }];
            //                [getGroupGignal subscribeError:^(NSError * _Nullable error) {
            //                    [self loginOut];
            //                    if (completionHandler) {
            //                        completionHandler(nil, error);
            //                    }
            //                }];
            //                [getFriednSignal subscribeError:^(NSError * _Nullable error) {
            //                    [self loginOut];
            //                    if (completionHandler) {
            //                        completionHandler(nil, error);
            //                    }
            //                }];
            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"firstInstall"];
            if (completionHandler) {
                completionHandler(x, nil);
            }
        }];
        [loginImSignal subscribeError:^(NSError * _Nullable error) {
            BDUserModel *tourUser = [BDUserModel getTouristsUser];
            [tourUser saveCurrentUser];
            if (completionHandler) {
                completionHandler(nil, error);
            }
        }];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        if (completionHandler) {
            completionHandler(nil, error);
        }
    }];
}

//- (RACCommand *)_getFriendList{
//    return [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
//        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
//            [JMSGFriendManager getFriendList:^(id resultObject, NSError *error) {
//                if (error) {
//                    NSError *newError = [NSError errorWithDomain:error.domain code:BDLoginErrorGetFirendsListFailed userInfo:error.userInfo];
//                    [subscriber sendError:newError];
//                }else{
//                    NSArray *friendList = (NSArray *)resultObject;
////                    [BDFMDBTool deleteTableWithClass:[BDFridentInfo class]];
////                    NSArray *friendList = [BDFridentInfo mj_objectArrayWithKeyValuesArray:x];
////                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
////                        [BDFMDBTool replaceWithObjectsArray:friendList];
////                    });
////                    self.unique_id = idfv;
////                    [self saveCurrentUser];
//                    [subscriber sendCompleted];
//                }
//            }];
//            return nil;
//        }];
//    }];
//}

//- (RACCommand *)_getGroupList{
//    return [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
//        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
//            //获取群列表
//            [JMSGGroup myGroupArray:^(id resultObject, NSError *error) {
//                if (error) {
//                    NSError *newError = [NSError errorWithDomain:error.domain code:BDLoginErrorGetGroupsListFailed userInfo:error.userInfo];
//                    [subscriber sendError:newError];
//                }else{
//                    NSArray *groupGidArray = (NSArray *)resultObject;
//                    NSMutableArray *dicGroupArray = [NSMutableArray array];
//                    for (NSString *groupGid in groupGidArray) {
//                        NSString *groupPath = [DocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"group_%@.plist", groupGid]];
////                        BDChatGroupModel *group = [[BDChatGroupModel alloc] init];
////                        group.groupid = groupGid;
////                        if ([group.mj_keyValues writeToFile:groupPath atomically:YES]) {
////                            [dicGroupArray addObject:group.groupid];
////                        }
//                    }if ([dicGroupArray writeToFile:GroupRefrencePath atomically:YES]) {
//                        [subscriber sendCompleted];
//                    }
//                }
//            }];
//
//            return nil;
//        }];
//    }];
//}

- (RACCommand *)_loginIM{
    return [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [self _loginIM:subscriber];
            return nil;
        }];
    }];
}

- (void)_loginIM:(id<RACSubscriber>  _Nonnull )subscriber{
    NSString *imId = [NSString stringWithFormat:@"%ld", (long)self.user_id];
    NSString *userName = [@"beboy_" stringByAppendingString:imId];
    [JMSGUser loginWithUsername:userName password:[BDMD5 MD5Encrypt:imId] completionHandler:^(id resultObject, NSError *error) {
        if (error) {
            if (error.code == 801003) {
                [JMSGUser registerWithUsername:userName password:[BDMD5 MD5Encrypt:imId] completionHandler:^(id resultObject, NSError *error) {
                    if (error) {
                        NSError *newError = [NSError errorWithDomain:error.domain code:BDLoginErrorLoginIMFailed userInfo:error.userInfo];
                        [subscriber sendError:newError];
                    }else{
                        [subscriber sendCompleted];
                    }
                }];
            }else{
                NSError *newError = [NSError errorWithDomain:error.domain code:BDLoginErrorLoginIMFailed userInfo:error.userInfo];
                [subscriber sendError:newError];
            }
        }else{
            [subscriber sendCompleted];
        }
    }];
}

+ (void)loginOut{
    [MBManager showLoadingAlert:ASLocalizedString(@"正在退出")clickHidden:NO clickBlock:nil];
    [JMSGUser logout:^(id resultObject, NSError *error) {
        BDUserModel *tourUser = [BDUserModel getTouristsUser];
        [tourUser saveCurrentUser];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBManager hideAlert];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUnreadCount" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginOutCurrentUser" object:@NO];
        });
    }];
}

+ (void)judgeCurrentUserWithNormalBlock:(void(^)())normalBlock{
    BDUserModel *curUser = [BDUserModel getCurrentUser];
    if (curUser.is_guest == YES) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"presentToLogin" object:nil];
    }else {
        if (normalBlock) {
            normalBlock();
        }
    }
    return;
}

//- (void)bindDeviceToken{
//    NSData *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentDeviceToken"];
//    [[EMClient sharedClient] registerForRemoteNotificationsWithDeviceToken:deviceToken completion:^(EMError *aError) {
//        if (aError == nil) {
//             BDLog(@"绑定token成功");
//        }else{
//             BDLog(@"绑定token失败");
//        }
//    }];
//}
@end
